// src/viewpage/View_page.tsx
import { message, Modal, Input, Select } from 'antd';
import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import Sidebar from '../Sidebar';
import Following from '../Mine/Following';
import Follower from '../Mine/Follower';
import Information from './information';
import ShowRecipe from './showrecipe';
import { FollowService } from './follow';
import { type UserProfile, type Recipe, type SearchOption, type SearchParams } from './types';
import backgroundImage from '../../src/assets/background2.jpg';

const { Option } = Select;

const View_page: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [recipes, setRecipes] = useState<Recipe[]>([]);
  const [loading, setLoading] = useState(true);
  const [isFollowing, setIsFollowing] = useState(false);
  const [followingModalVisible, setFollowingModalVisible] = useState(false);
  const [followerModalVisible, setFollowerModalVisible] = useState(false);
  const [currentTab, setCurrentTab] = useState<'食谱' | '收藏'>('食谱');
  const [followCount, setFollowCount] = useState(0);
  const [followerCount, setFollowerCount] = useState(0);
  
  // 搜索相关状态
  const [searchModalVisible, setSearchModalVisible] = useState(false);
  const [searchMethod, setSearchMethod] = useState<'keyword' | 'time' | 'cuisine' | 'ingredient'>('keyword');
  const [searchValue, setSearchValue] = useState('');
  const [searchLoading, setSearchLoading] = useState(false);
  const [isSearchResult, setIsSearchResult] = useState(false);

  const targetUserId = id;

  // 搜索选项配置
  const searchOptions: SearchOption[] = [
    {
      key: 'keyword',
      label: '菜名关键词',
      type: 'input',
      placeholder: '请输入菜名关键词'
    },
    {
      key: 'time',
      label: '时段',
      type: 'select',
      options: [
        { value: '早餐', label: '早餐' },
        { value: '午餐', label: '午餐' },
        { value: '晚餐', label: '晚餐' },
        { value: '下午茶', label: '下午茶' }
      ]
    },
    {
      key: 'cuisine',
      label: '菜系',
      type: 'select',
      options: [
        { value: '粤菜', label: '粤菜' },
        { value: '川菜', label: '川菜' },
        { value: '鲁菜', label: '鲁菜' },
        { value: '徽菜', label: '徽菜' },
        { value: '闽菜', label: '闽菜' },
        { value: '湘菜', label: '湘菜' },
        { value: '浙菜', label: '浙菜' },
        { value: '淮扬菜', label: '淮扬菜' }
      ]
    },
    {
      key: 'ingredient',
      label: '食材',
      type: 'input',
      placeholder: '请输入食材名称'
    }
  ];

  // 获取搜索方法的文本描述
  const getSearchMethodText = (method: string) => {
    const methodMap: Record<string, string> = {
      'keyword': '菜名',
      'time': '时段',
      'cuisine': '菜系',
      'ingredient': '食材'
    };
    return methodMap[method] || '相关';
  };

  const isCurrentUser = () => {
    const currentUserId = localStorage.getItem('userId');
    return currentUserId === targetUserId;
  };

  // 获取用户菜谱函数
  const fetchUserRecipes = async (userId: string, token: string) => {
    try {
      const recipesResponse = await fetch(`/api/recipe/user/${userId}`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });
      
      if (recipesResponse.ok) {
        const recipesData = await recipesResponse.json();
        console.log('用户菜谱数据:', recipesData);
        
        if (Array.isArray(recipesData)) {
          const formattedRecipes = recipesData.map((recipe: any) => ({
            id: recipe.id || recipe.recipeId,
            title: recipe.title || recipe.recipeName || '未命名菜谱',
            image: recipe.image || recipe.coverImage || recipe.photo,
            description: recipe.description,
            duration: recipe.duration,
            difficulty: recipe.difficulty,
            servings: recipe.servings,
            likesCount: recipe.likesCount,
            favoriteCount: recipe.favoriteCount,
            userId: recipe.userId,
            createdAt: recipe.createdAt,
            updatedAt: recipe.updatedAt
          }));
          setRecipes(formattedRecipes);
          return formattedRecipes.length;
        } else {
          setRecipes([]);
          return 0;
        }
      } else {
        setRecipes([]);
        return 0;
      }
    } catch (error) {
      console.log('获取用户菜谱失败:', error);
      setRecipes([]);
      return 0;
    }
  };

  // 搜索该用户发布的菜谱函数（前端过滤版本）
  const searchRecipes = async (params: SearchParams) => {
    try {
      setSearchLoading(true);
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      if (!token) {
        message.warning('请先登录');
        return;
      }

      let apiParamName = '';
      switch (params.method) {
        case 'keyword':
          apiParamName = 'keyword';
          break;
        case 'time':
          apiParamName = 'tag';
          break;
        case 'cuisine':
          apiParamName = 'category';
          break;
        case 'ingredient':
          apiParamName = 'ingredient';
          break;
      }

      const queryParams = new URLSearchParams();
      queryParams.append(apiParamName, params.value);

      const response = await fetch(`/api/recipe/search?${queryParams.toString()}`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const recipesData = await response.json();
        console.log('搜索菜谱数据:', recipesData);
        
        if (Array.isArray(recipesData) && recipesData.length > 0) {
          // 前端过滤：只显示该用户发布的菜谱
          const userRecipes = recipesData.filter((recipe: any) => 
            recipe.userId === parseInt(targetUserId!) || 
            recipe.userId === targetUserId
          );
          
          if (userRecipes.length > 0) {
            const formattedRecipes = userRecipes.map((recipe: any) => ({
              id: recipe.id || recipe.recipeId,
              title: recipe.title || recipe.recipeName || '未命名菜谱',
              image: recipe.image || recipe.coverImage || recipe.photo,
              description: recipe.description,
              duration: recipe.duration,
              difficulty: recipe.difficulty,
              servings: recipe.servings,
              likesCount: recipe.likesCount,
              favoriteCount: recipe.favoriteCount,
              userId: recipe.userId,
              createdAt: recipe.createdAt,
              updatedAt: recipe.updatedAt
            }));
            setRecipes(formattedRecipes);
            setIsSearchResult(true);
            message.success(`找到 ${formattedRecipes.length} 个相关菜谱`);
          } else {
            // 没有找到该用户的菜谱
            setRecipes([]);
            setIsSearchResult(true);
            message.info(`未找到${getSearchMethodText(searchMethod)}为"${searchValue}"的菜谱`);
          }
        } else {
          // 搜索为空时，清空列表并显示提示
          setRecipes([]);
          setIsSearchResult(true);
          message.info(`未找到${getSearchMethodText(searchMethod)}为"${searchValue}"的菜谱`);
        }
      } else {
        message.error('搜索失败');
      }
    } catch (error) {
      console.error('搜索菜谱失败:', error);
      message.error('搜索失败，请重试');
    } finally {
      setSearchLoading(false);
    }
  };

  const fetchFollowingRecipes = async () => {
    if (currentTab !== '收藏') return;
    
    try {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      if (!token || !targetUserId) return;

      const response = await fetch(`/api/userfollows/following/${targetUserId}/recipes`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const recipesData = await response.json();
        console.log('收藏菜谱数据:', recipesData); 
        if (Array.isArray(recipesData)) {
          const formattedRecipes = recipesData.map((recipe: any) => ({
            id: recipe.id || recipe.recipeId,
            title: recipe.title || recipe.recipeName || '未命名菜谱',
            image: recipe.image || recipe.coverImage || recipe.photo,
            description: recipe.description,
            duration: recipe.duration,
            difficulty: recipe.difficulty,
            servings: recipe.servings,
            likesCount: recipe.likesCount,
            favoriteCount: recipe.favoriteCount,
            userId: recipe.userId,
            createdAt: recipe.createdAt,
            updatedAt: recipe.updatedAt
          }));
          setRecipes(formattedRecipes);
        } else {
          setRecipes([]);
        }
      }
    } catch (error) {
      console.log('获取收藏菜谱失败:', error);
      setRecipes([]);
    }
  };

  // 处理搜索点击
  const handleSearchClick = () => {
    setSearchModalVisible(true);
    setSearchMethod('keyword');
    setSearchValue('');
  };

  // 处理搜索提交
  const handleSearchSubmit = () => {
    if (!searchValue.trim()) {
      message.warning('请输入搜索内容');
      return;
    }

    searchRecipes({
      method: searchMethod,
      value: searchValue
    });
    setSearchModalVisible(false);
  };

  // 处理搜索方法变更
  const handleSearchMethodChange = (method: 'keyword' | 'time' | 'cuisine' | 'ingredient') => {
    setSearchMethod(method);
    setSearchValue('');
  };

  // 重置搜索并显示用户菜谱
  const handleResetSearch = async () => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (token && targetUserId) {
      setSearchLoading(true);
      try {
        await fetchUserRecipes(targetUserId, token);
        setIsSearchResult(false);
        message.success('已显示全部菜谱');
      } catch (error) {
        console.error('重置搜索失败:', error);
        message.error('重置失败，请重试');
      } finally {
        setSearchLoading(false);
      }
    }
  };

  useEffect(() => {
    const fetchUserProfile = async () => {
      try {
        setLoading(true);
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        
        if (!token || !targetUserId) {
          message.warning('请先登录');
          navigate('/login');
          return;
        }

        let userData;
        
        try {
          const userDetailResponse = await fetch(`/api/users/${targetUserId}`, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });
          
          if (userDetailResponse.ok) {
            userData = await userDetailResponse.json();
            console.log('用户详情接口返回:', userData); 
          } else {
            throw new Error('用户详情接口失败');
          }
        } catch (error) {
          console.log('用户详情接口失败，尝试搜索接口:', error);
          const userResponse = await fetch(`/api/users/search?uid=${targetUserId}`, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });
          
          if (userResponse.ok) {
            const searchResult = await userResponse.json();
            console.log('搜索接口返回:', searchResult); 
            
            if (Array.isArray(searchResult) && searchResult.length > 0) {
              userData = searchResult[0];
            } else if (searchResult && typeof searchResult === 'object') {
              userData = searchResult;
            }
          }
        }

        const recipeCount = await fetchUserRecipes(targetUserId, token);

        const processedUserData: UserProfile = {
          id: userData?.id || userData?.userId || userData?.user_id || parseInt(targetUserId),
          username: userData?.username || userData?.account || userData?.userName || `user${targetUserId}`,
          nickname: userData?.nickname || userData?.name || userData?.nickName || userData?.username || `用户${targetUserId}`,
          avatar: userData?.avatar || userData?.avatarUrl || userData?.avatar_url || userData?.profilePicture || userData?.profile_picture,
          followCount: userData?.followCount || userData?.followingCount || userData?.following_count || userData?.following || 0,
          followerCount: userData?.followerCount || userData?.fansCount || userData?.fans_count || userData?.followers || 0,
          recipeCount: userData?.recipeCount || userData?.postCount || userData?.post_count || userData?.recipe_count || recipeCount || 0
        };

        console.log('处理后的用户数据:', processedUserData);
        setUserProfile(processedUserData);
        
        const { followCount, followerCount } = await FollowService.fetchFollowCounts(targetUserId, token);
        setFollowCount(followCount);
        setFollowerCount(followerCount);
        
        const followingStatus = await FollowService.checkIfFollowing(parseInt(targetUserId), token);
        setIsFollowing(followingStatus);

      } catch (error) {
        console.error('获取用户信息失败:', error);
        const fallbackUser: UserProfile = {
          id: parseInt(targetUserId || '0'),
          username: `user${targetUserId}`,
          nickname: `用户${targetUserId}`,
          followCount: 0,
          followerCount: 0,
          recipeCount: recipes.length
        };
        setUserProfile(fallbackUser);
        setRecipes([]);
      } finally {
        setLoading(false);
      }
    };

    if (targetUserId) {
      fetchUserProfile();
    }
  }, [targetUserId, navigate]);

  useEffect(() => {
    if (targetUserId && currentTab === '收藏') {
      fetchFollowingRecipes();
    } else if (targetUserId && currentTab === '食谱') {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      if (token) {
        fetchUserRecipes(targetUserId, token);
      }
    }
  }, [currentTab, targetUserId]);

  const handleBack = () => navigate(-1);

  const handleFollow = async () => {
    if (!userProfile) return;
    await FollowService.handleFollow(userProfile, isFollowing, setIsFollowing, setFollowerCount);
  };

  const handleFollowCountClick = () => {
    if (isCurrentUser()) {
      setFollowingModalVisible(true);
    } else {
      message.info('无法查看他人的关注列表');
    }
  };

  const handleFollowerCountClick = () => {
    if (isCurrentUser()) {
      setFollowerModalVisible(true);
    } else {
      message.info('无法查看他人的粉丝列表');
    }
  };

  const handleRecipeClick = (recipe: Recipe) => {
    console.log('点击菜谱:', recipe);
    navigate(`/recipe/${recipe.id}`, { state: { recipe } });
  };

  const handleTabChange = (tab: '食谱' | '收藏') => {
    setCurrentTab(tab);
    setIsSearchResult(false);
  };

  // 获取当前搜索选项
  const currentSearchOption = searchOptions.find(option => option.key === searchMethod);

  if (loading) {
    return (
      <div style={{ 
        padding: '20px', 
        textAlign: 'center',
        backgroundImage: `url(${backgroundImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        <div style={{
          padding: '30px',
          backgroundColor: 'rgba(255,255,255,0.8)',
          borderRadius: '20px',
          boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
          fontSize: '18px',
          color: '#666',
          backdropFilter: 'blur(10px)'
        }}>
          正在加载用户信息...
        </div>
      </div>
    );
  }

  if (!userProfile) {
    return (
      <div style={{ 
        padding: '20px', 
        textAlign: 'center',
        backgroundImage: `url(${backgroundImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        <div style={{
          padding: '30px',
          backgroundColor: 'rgba(255,255,255,0.8)',
          borderRadius: '20px',
          boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
          fontSize: '18px',
          color: '#666',
          backdropFilter: 'blur(10px)'
        }}>
          用户信息加载失败
        </div>
      </div>
    );
  }

  const followInfo = {
    followCount,
    followerCount,
    isFollowing
  };

  return (
    <div style={{ 
      display: 'flex', 
      height: '100vh', 
      backgroundImage: `url(${backgroundImage})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      position: 'relative'
    }}>
      <Sidebar />

      <div style={{ 
        flex: 1, 
        padding: '30px', 
        overflowY: 'auto'
      }}>
        <Information
          userProfile={userProfile}
          followInfo={followInfo}
          isCurrentUser={isCurrentUser()}
          onFollow={handleFollow}
          onFollowCountClick={handleFollowCountClick}
          onFollowerCountClick={handleFollowerCountClick}
          onBack={handleBack}
          onSearchClick={handleSearchClick}
        />

        {/* 搜索状态提示和重置按钮 */}
        {(isSearchResult || searchLoading) && (
          <div style={{ 
            textAlign: 'center', 
            marginBottom: '20px',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: '15px'
          }}>
            {searchLoading ? (
              <div style={{
                padding: '10px 20px',
                backgroundColor: 'rgba(255,255,255,0.8)',
                borderRadius: '20px',
                color: '#8B4513',
                fontSize: '14px',
                backdropFilter: 'blur(10px)'
              }}>
                搜索中...
              </div>
            ) : isSearchResult ? (
              <>
                {recipes.length > 0 ? (
                  <div style={{
                    padding: '10px 20px',
                    backgroundColor: 'rgba(255,255,255,0.8)',
                    borderRadius: '20px',
                    color: '#8B4513',
                    fontSize: '14px',
                    backdropFilter: 'blur(10px)'
                  }}>
                    当前显示搜索结果（{recipes.length}个菜谱）
                  </div>
                ) : (
                  <div style={{
                    padding: '10px 20px',
                    backgroundColor: 'rgba(255,253,248,0.9)',
                    borderRadius: '20px',
                    color: '#8B7D6B',
                    fontSize: '14px',
                    border: '1px solid #e8d5b5',
                    backdropFilter: 'blur(10px)'
                  }}>
                    未找到符合条件的菜谱
                  </div>
                )}
                <button
                  onClick={handleResetSearch}
                  style={{
                    background: 'linear-gradient(135deg, rgba(240,224,208,0.8) 0%, rgba(232,208,184,0.8) 100%)',
                    border: 'none',
                    borderRadius: '20px',
                    padding: '10px 20px',
                    fontSize: '14px',
                    fontWeight: '600',
                    cursor: 'pointer',
                    color: '#8B4513',
                    boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                    backdropFilter: 'blur(10px)'
                  }}
                >
                  显示全部菜谱
                </button>
              </>
            ) : null}
          </div>
        )}

        <ShowRecipe
          recipes={recipes}
          currentTab={currentTab}
          onRecipeClick={handleRecipeClick}
          onTabChange={handleTabChange}
          showCollectTab={isCurrentUser()}
        />
      </div>

      {isCurrentUser() && (
        <>
          <Following
            visible={followingModalVisible}
            onClose={() => setFollowingModalVisible(false)}
            userId={userProfile.id}
          />
          <Follower
            visible={followerModalVisible}
            onClose={() => setFollowerModalVisible(false)}
            userId={userProfile.id}
          />
        </>
      )}

      {/* 搜索模态框 */}
      <Modal
        title={`搜索${userProfile.nickname}的菜谱`}
        open={searchModalVisible}
        onOk={handleSearchSubmit}
        onCancel={() => setSearchModalVisible(false)}
        confirmLoading={searchLoading}
        okText="搜索"
        cancelText="取消"
        styles={{
          body: {
            padding: '20px 0'
          }
        }}
      >
        <div style={{ marginBottom: '16px' }}>
          <label style={{ display: 'block', marginBottom: '8px', fontWeight: '600', color: '#8B4513' }}>
            搜索条件:
          </label>
          <Select
            value={searchMethod}
            onChange={handleSearchMethodChange}
            style={{ width: '100%' }}
          >
            {searchOptions.map(option => (
              <Option key={option.key} value={option.key}>
                {option.label}
              </Option>
            ))}
          </Select>
        </div>

        <div>
          <label style={{ display: 'block', marginBottom: '8px', fontWeight: '600', color: '#8B4513' }}>
            搜索内容:
          </label>
          {currentSearchOption?.type === 'input' ? (
            <Input
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
              placeholder={currentSearchOption?.placeholder}
              onPressEnter={handleSearchSubmit}
            />
          ) : (
            <Select
              value={searchValue}
              onChange={setSearchValue}
              style={{ width: '100%' }}
              placeholder={`请选择${currentSearchOption?.label}`}
            >
              {currentSearchOption?.options?.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          )}
        </div>
        
        {/* 添加搜索范围提示 */}
        <div style={{ 
          marginTop: '12px', 
          padding: '8px 12px', 
          backgroundColor: '#f9f5f0', 
          borderRadius: '6px',
          fontSize: '12px',
          color: '#8B7D6B'
        }}>
          仅搜索{userProfile.nickname}发布的菜谱
        </div>
      </Modal>
    </div>
  );
};

export default View_page;